package com.example.letgo.Fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.letgo.Application.ClearEditText;
import com.example.letgo.R;
import com.example.letgo.global.Constant;
import com.example.letgo.model.Team;
import com.example.letgo.model.User;
import com.example.letgo.trip.TripDetailsActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import okhttp3.Call;

import okhttp3.Response;

/**
 * Created by cc on 2018/2/3.
 */

public class TripFragment extends Fragment {
    private static TripFragment instance = null;
    private ListView listView;
    private ClearEditText search;
    private SwipeRefreshLayout swipeRefreshLayout ;
    private ArrayList<Map<String, Object>> lists=new ArrayList<Map<String,Object>>();


    //过滤相关
    /**
     * 过滤器上的锁可以同步复制原始数据。
     */
    private ArrayList<Map<String, Object>> mOriginalValues;
//    private Mybaseadapter.ArrayFilter mFilter;

    public TripFragment() {
        // Required empty public constructor

    }

    /**
     * IM需要的返回实例化的对象-hbl
     * @return
     */
    public static TripFragment getInstance(){
        if (instance==null){
            instance = new TripFragment();
        }
        return instance;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // 实例化
        View view = inflater.inflate(R.layout.fragment_trip, container, false);
        listView = (ListView)view.findViewById(R.id.trip_listview);
        swipeRefreshLayout  = view.findViewById(R.id.trip_xiala);

        View headView = getActivity().getLayoutInflater().inflate(R.layout.listhead_trip, null);
        View footView = getActivity().getLayoutInflater().inflate(R.layout.tripfooter,null);
        search = (ClearEditText)view.findViewById(R.id.search_text);

        init();

        listView.addHeaderView(headView,null,false);
        listView.addFooterView(footView,null,false);
        intiEditView();
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                        Toast.makeText(getActivity(), "刷新完成 !", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },1000);
            }
        });
        Log.i("ID",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>    "+ Constant.id);
        return view;
    }


    //   监听搜索框 并调用搜索适配器
    private void intiEditView() {
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                mAdapter.getFilter().filter(s);

                String searchtext = search.getText().toString();
                Log.i("Tag",searchtext);
                if ( searchtext.equals("")){

                    Log.i("Tag",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        init();
                }else {
                    searchinit();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //    搜索时调用 ------------------------------------------------------------------
    private void searchinit(){
        OkGo.get("http://119.29.113.114:8080/gogogo/team")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("s",s);
                        Gson gson = new Gson();
                        Type listType = new TypeToken<LinkedList<Team>>(){}.getType();
                        LinkedList<Team> list = gson.fromJson(s, listType);
                        Map<String, Object>map=new HashMap<String, Object>();
                        lists.clear();
                        for (int i = 0;i<list.size();i++){
                            if (list.get(i).getTeamOverPlace().equals(search.getText().toString())) {
                                Log.i("TAG",search.getText().toString());

                                int teamUserId = list.get(i).getTeamUserId();
                                String teamOverPlace = list.get(i).getTeamOverPlace();
                                String teamText = list.get(i).getTeamText();
                                String teamImage = "http://119.29.113.114:8080/gogogo/"+list.get(i).getTeamImage();
                                String teamDescribe = list.get(i).getTeamDescribe();
                                String teamStartPlace = list.get(i).getTeamStartPlace();
                                String teamTime = list.get(i).getTeamTime();
                                String teamDate = list.get(i).getTeamDate();
                                String teamSex = list.get(i).getTeamSex();
                                String teamMoney = list.get(i).getTeamMoney();
                                String teamPersons = list.get(i).getTeamPersons();
                                map.put("teamUserId",teamUserId);
                                map.put("teamTime",teamTime);
                                map.put("teamImage", teamImage);
                                map.put("teamOverPlace",teamOverPlace);
                                map.put("teamDescribe",teamDescribe);
                                map.put("teamText",teamText);
                                map.put("teamStartPlace",teamStartPlace);
                                map.put("teamDate",teamDate);
                                map.put("teamSex",teamSex);
                                map.put("teamMoney",teamMoney);
                                map.put("teamPersons",teamPersons);
                                lists.add(map);
                            }
                        }
                        //  调用适配器
                        listView.setAdapter(new Searchadapter());
                    }
                });
    }

    //   搜索 加载的适配器
    public class Searchadapter extends BaseAdapter{

        @Override
        public int getCount() {
            return lists.size();
        }
        @Override
        public Object getItem(int position) {
            if (lists!= null && lists.size() > position) {
                return lists.get(position);
            } else {
                return null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        // Picasso图片加载框架 进行加载
        @SuppressLint("RestrictedApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

                ViewHolder viewHolder = null;
                if (convertView == null) {
                    viewHolder = new ViewHolder();
                    convertView = getActivity().getLayoutInflater().inflate(R.layout.listview_trip, null);
                    viewHolder.img = convertView.findViewById(R.id.image);
                    viewHolder.destination = convertView.findViewById(R.id.title);
                    viewHolder.describe = convertView.findViewById(R.id.list_text);


                    convertView.setTag(viewHolder);
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }
                //判断获取的json中图片是否为空
                if (TextUtils.isEmpty(lists.get(position).get("teamImage").toString())) {
                    Picasso
                            .with(getActivity())
                            .cancelRequest(viewHolder.img);
                    viewHolder.img.setImageDrawable(getResources().getDrawable(R.drawable.loading));//当图片为空时显示
                } else {
                    //图片加载
                    Picasso
                            .with(getActivity())
                            .load(lists.get(position).get("teamImage").toString())
                            .placeholder(R.drawable.loading)//图片加载中显示
                            .into(viewHolder.img);
                }
                viewHolder.destination.setText(lists.get(position).get("teamOverPlace").toString());
                viewHolder.describe.setText(lists.get(position).get("teamDescribe").toString());
            Toast.makeText(getActivity(), "搜索成功！", Toast.LENGTH_SHORT).show();

                //  为item设置点击事件， 并传递参数
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Bundle bundle = new Bundle();
                        bundle.putString("position", String.valueOf(position));
                        bundle.putInt("teamId", Integer.valueOf(lists.get(position-1).get("teamId").toString()) );
                        bundle.putInt("teamUserId", Integer.valueOf(lists.get(position-1).get("teamUserId").toString()));
                        bundle.putString("teamTime", lists.get(position - 1).get("teamTime").toString());
                        bundle.putString("teamOverPlace", lists.get(position - 1).get("teamOverPlace").toString());
                        bundle.putString("teamDescribe", lists.get(position - 1).get("teamDescribe").toString());
                        bundle.putString("teamText", lists.get(position - 1).get("teamText").toString());
                        bundle.putString("teamStartPlace", lists.get(position - 1).get("teamStartPlace").toString());
                        bundle.putString("teamDate", lists.get(position - 1).get("teamDate").toString());
                        bundle.putString("teamSex", lists.get(position - 1).get("teamSex").toString());
                        bundle.putString("teamMoney", lists.get(position - 1).get("teamMoney").toString());
                        bundle.putString("teamPersons", lists.get(position - 1).get("teamPersons").toString());

                        bundle.putString("teamImage", lists.get(position - 1).get("teamImage").toString());
                        Intent produceinfo = new Intent(getActivity(), TripDetailsActivity.class);
                        produceinfo.putExtras(bundle);
                        startActivity(produceinfo);
                    }

                });
            return convertView;
        }
    }

//   默认数据加载调用 ---------------------------------------------------------------------------

    private void init() {
        OkGo.get("http://119.29.113.114:8080/gogogo/team")
                    .execute(new StringCallback() {
                             @Override
                             public void onSuccess(String s, Call call, Response response) {
                                 Log.e("s",s);
                                 Gson gson = new Gson();
                                 Type listType = new TypeToken<LinkedList<Team>>(){}.getType();
                                 LinkedList<Team> list = gson.fromJson(s, listType);
                                 //  调用适配器

                                 listView.setAdapter(new Mybaseadapter(list));

                             }
                });
    }


    public class Mybaseadapter extends BaseAdapter {

        LinkedList<Team> list;

        public Mybaseadapter(LinkedList<Team> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public Object getItem(int position) {
            if (list != null && list.size() > position) {
                return list.get(position);
            } else {
                return null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        // Picasso图片加载框架 进行加载
        @SuppressLint("RestrictedApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getActivity().getLayoutInflater().inflate(R.layout.listview_trip, null);
                viewHolder.img =  convertView.findViewById(R.id.image);
                viewHolder.destination = convertView.findViewById(R.id.title);
                viewHolder.describe = convertView.findViewById(R.id.list_text);


                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //判断获取的json中图片是否为空
            if (TextUtils.isEmpty("http://119.29.113.114:8080/gogogo/"+list.get(position).getTeamImage())){
                Picasso
                        .with(getActivity())
                        .cancelRequest(viewHolder.img);
                viewHolder.img.setImageDrawable(getResources().getDrawable(R.drawable.loading));//当图片为空时显示
            }else {
                //图片加载
                Picasso
                        .with(getActivity())
                        .load("http://119.29.113.114:8080/gogogo/"+list.get(position).getTeamImage())
                        .placeholder(R.drawable.loading)//图片加载中显示
                        .into(viewHolder.img);
            }
            viewHolder.destination.setText(list.get(position).getTeamOverPlace());
            viewHolder.describe.setText(list.get(position).getTeamDescribe());

            //  为item设置点击事件， 并传递参数
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Bundle bundle = new Bundle();
                    bundle.putString("position", String.valueOf(position-1));
                    bundle.putInt("teamId", list.get(position-1).getTeamId());
                    bundle.putInt("teamUserId", list.get(position-1).getTeamUserId());
                    bundle.putString("teamTime", list.get(position - 1).getTeamTime());
                    bundle.putString("teamOverPlace", list.get(position-1).getTeamOverPlace());
                    bundle.putString("teamDescribe", list.get(position-1).getTeamDescribe());
                    bundle.putString("teamText", list.get(position-1).getTeamText());
                    bundle.putString("teamStartPlace", list.get(position-1).getTeamStartPlace());
                    bundle.putString("teamDate", list.get(position-1).getTeamDate());
                    bundle.putString("teamSex",  list.get(position-1).getTeamSex());
                    bundle.putString("teamMoney", list.get(position-1).getTeamMoney());
                    bundle.putString("teamPersons", list.get(position-1).getTeamPersons());

                    bundle.putString("teamImage", "http://119.29.113.114:8080/gogogo/"+list.get(position-1).getTeamImage());
                    Intent produceinfo = new Intent(getActivity(), TripDetailsActivity.class);
                    produceinfo.putExtras(bundle);
                    startActivity(produceinfo);
                }

            });
            return convertView;
        }

    }


    final static class ViewHolder {
        TextView destination;
        TextView describe;
        ImageView img;
    }


}






